import time

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from flask_cors import CORS
from flask import Flask, request, json

app = Flask('51tracking-airlines-service')
CORS(app)


def createChromeDriver():
    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_argument('--headless')
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--disable-dev-shm-usage')

    # 将--user-data-dir改为自定义目录
    # 在linux服务器上执行，需要增加
    # chrome_options.add_argument("--user-data-dir=/root/51tracking-airlines")
    # s = Service(executable_path='/usr/local/bin/chromedriver')

    s = Service(executable_path='/Users/gilbert/chromedriver-mac-x64/chromedriver')
    _chrome_driver_instance = webdriver.Chrome(service=s, options=chrome_options)

    _chrome_driver_instance.maximize_window()

    return _chrome_driver_instance


def scrapyAirlinesInfo(awb):
    chrome_driver_instance = createChromeDriver()

    try:
        chrome_driver_instance.get("https://www.51tracking.com/aircargo/cn/" + str(awb))

        time.sleep(8)

        flightNo = chrome_driver_instance.find_element(By.XPATH,
                                                       "//tbody[tr[1]/td[1]='航班']/tr[2]/td[1]").text
        source = chrome_driver_instance.find_element(By.XPATH,
                                                     "//tbody[tr[1]/td[2]='出发站']/tr[2]/td[2]").text
        destination = chrome_driver_instance.find_element(By.XPATH,
                                                          "//tbody[tr[1]/td[3]='到达站']/tr[2]/td[3]").text
        scheduleDepartureTime = chrome_driver_instance.find_element(By.XPATH,
                                                                    "//tbody[tr[1]/td[4]='预离时间']/tr[2]/td[4]").text
        estimatedArrivalTime = chrome_driver_instance.find_element(By.XPATH,
                                                                   "//tbody[tr[1]/td[5]='预抵时间']/tr[2]/td[5]").text
        departureTime = chrome_driver_instance.find_element(By.XPATH,
                                                            "//tbody[tr[1]/td[6]='起飞时间']/tr[2]/td[6]").text
        arrivalTime = chrome_driver_instance.find_element(By.XPATH,
                                                          "//tbody[tr[1]/td[7]='抵达时间']/tr[2]/td[7]").text
        return {
            "result": "SUCCESS",
            "data": {
                "flightNo": flightNo,
                "source": source,
                "destination": destination,
                "scheduledDepartureTime": scheduleDepartureTime,
                "estimatedArrivalTime": estimatedArrivalTime,
                "departureTime": departureTime,
                "arrivalTime": arrivalTime
            }
        }

    except Exception as e:
        return {
            "result": "FAILED",
            "error": e.__str__()
        }
    finally:
        chrome_driver_instance.quit()


@app.route('/getAirlineInfo', methods=['POST'])
def getRoutes():
    data = json.loads(json.dumps(request.get_json()))

    return scrapyAirlinesInfo(data['awb'])


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=10010, debug=False)
